﻿using System;
using System.Linq;
using System.Web.UI.WebControls;
using System.ComponentModel;

namespace MyLib.Web.UI {
	/// <summary>
	/// 
	/// </summary>
	public class MyDropDownList : DropDownList {
		/// <summary>
		/// 
		/// </summary>
		public override string SelectedValue {
			get {
				return base.SelectedValue;
			}
			set {
				try {
					base.SelectedValue = value;
				} catch (ArgumentOutOfRangeException) {
					base.SelectedValue = null;
				}
			}
		}

		/// <summary>
		/// 
		/// </summary>
		[Bindable(true)]
		[Browsable(true)]
		[Category("Action")]
		[DefaultValue(false)]
		public virtual bool PrependNoneCode {
			get {
				var obj = ViewState["PrependNoneCode"];
				if (obj == null) {
					return false;
				} else {
					return (bool)obj;
				}
			}
			set {
				ViewState["PrependNoneCode"] = value;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		[Bindable(true)]
		[Browsable(true)]
		[Category("Action")]
		[DefaultValue(false)]
		public virtual bool PrependAllCode {
			get {
				var obj = ViewState["PrependAllCode"];
				if (obj == null) {
					return false;
				} else {
					return (bool)obj;
				}
			}
			set {
				ViewState["PrependAllCode"] = value;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="dataSource"></param>
		protected override void PerformDataBinding(System.Collections.IEnumerable dataSource) {
			try {
				if (PrependAllCode || PrependNoneCode) {
					// Prepend code.
					System.Data.DataTable dt = null;
					if (dataSource is System.Data.DataView) {
						dt = ((System.Data.DataView)dataSource).ToTable(true);
					} else if (dataSource is System.Data.DataTable) {
						dt = (System.Data.DataTable)dataSource;
					}

					if (dt != null) {
						dt.BeginInit();
						
						var dvf = dt.Columns[DataValueField];
						dvf.AllowDBNull = true;
						if(dt.PrimaryKey != null && dt.PrimaryKey.Contains(dvf)) {
							dt.PrimaryKey = dt.PrimaryKey.Where(f => f != dvf).ToArray();
						}

						dt.EndInit();

						dt.BeginLoadData();

						var row = dt.NewRow();
						if (PrependAllCode) {
							row[DataTextField] = Properties.Main.AllCodeText;
							row[DataValueField] = DBNull.Value;
						} else if (PrependNoneCode) {
							row[DataTextField] = Properties.Main.EmptyCodeText;
							row[DataValueField] = DBNull.Value;
						}
						dt.Rows.InsertAt(row, 0);

						dt.AcceptChanges();
						dt.EndLoadData();

						base.PerformDataBinding(dt.DefaultView);
					} else {
						base.PerformDataBinding(dataSource);
					}
				} else {
					base.PerformDataBinding(dataSource);
				}
			} catch (ArgumentOutOfRangeException) {
				base.SelectedValue = null;
			}
		}
	} // end of MyDropDownList.
}
